<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        margin: 0 auto;
      }
      .box > div {
        width: 100px;
        border: 3px solid;
      }

      .box > div > div {
        margin-left: 10px;
        color: green;
      }

      .box > div > div > div {
        margin-left: 20px;

        color: red;
      }

      .box > div > div > div > div {
        margin-left: 30px;
        color: aqua;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
  </body>
</html>
<script>
  //服务器返回一个不确定的数据结构,涉及到多重数组嵌套
  let resData = [
    {
      type: "电子产品",
      data: [
        {
          type: "手机",
          data: ["iPhone手机", "小米手机", "华为手机"],
        },
        {
          type: "平板",
          data: ["iPad", "平板小米", "平板华为"],
        },
        {
          type: "智能手表",
          data: [],
        },
      ],
    },
    {
      type: "生活家居",
      data: [
        {
          type: "沙发",
          data: ["真皮沙发", "布沙发"],
        },
        {
          type: "椅子",
          data: ["餐椅", "电脑椅", "办公椅", "休闲椅"],
        },
        {
          type: "桌子",
          data: ["办公桌"],
        },
      ],
    },
    {
      type: "零食",
      data: [
        {
          type: "水果",
          data: [],
        },
        {
          type: "咖啡",
          data: ["雀巢咖啡"],
        },
      ],
    },
  ];
  const Box = document.querySelector(".box");
  function createTree(resData, prevItem) {
    const fragment = document.createDocumentFragment();
    for (let i = 0; i < resData.length; i++) {
      let item = document.createElement("div");
      item.innerHTML = `<p>${resData[i].type || resData[i]}</p>`;
      if (resData[i].data) {
        createTree(resData[i].data, item);
      }
      if (prevItem) prevItem.appendChild(item);
    }
    if (prevItem) {
      fragment.appendChild(prevItem);
      Box.appendChild(fragment);
    }
  }
  createTree(resData, null);
</script>
